<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<% String path=request.getContextPath(); String basePath=request.getScheme()+ "://" + request.getServerName() + ":" + request.getServerPort() + path+ "/"; %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" >
<html  xmlns="http://www.w3.org/1999/xhtml"> 
<head>
<base href="<%=basePath%>">
<title>信保开关</title>
	<%@ include file="/WEB-INF/jsp/common/common.jsp" %>
	<script src="<%=path%>/js/jquery.divbox.js" type="text/javascript"></script>
	<script src="js/json2.js" type="text/javascript"></script>
	<script type="text/javascript">
	//自定义map功能
	function Map(){
	  this.elements = new Array();
	   //获取MAP元素个数
	   this.size = function() {
	       return this.elements.length;
	   };
	   //判断MAP是否为空
	   this.isEmpty = function() {
	       return (this.elements.length < 1);
	   };
	   //删除MAP所有元素
	   this.clear = function() {
	       this.elements = new Array();
	   };
	   //向MAP中增加元素（key, value)
	   this.put = function(_key, _value) {
	       if(this.containsKey(_key)){
	        this.remove(_key);
	        this.elements.push( {
	           key : _key,
	           value : _value
	        });
	       }else{
	        this.elements.push( {
	           key : _key,
	           value : _value
	        });
	       }  
	   };
	   //删除指定KEY的元素，成功返回True，失败返回False
	   this.remove = function(_key) {
	       var bln = false;
	       try {
	           for (var i = 0; i < this.elements.length; i++) {
	               if (this.elements[i].key == _key) {
	                   this.elements.splice(i, 1);
	                   return true;
	               }
	           }
	       } catch (e) {
	           bln = false;
	       }
	       return bln;
	   };
	   //获取指定KEY的元素值VALUE，失败返回NULL
	   this.get = function(_key) {
	       try {
	           for (var i = 0; i < this.elements.length; i++) {
	               if (this.elements[i].key == _key) {
	                   return this.elements[i].value;
	               }
	           }
	       } catch (e) {
	           return false;
	       }
	       return false;
	   };
	   //判断MAP中是否含有指定KEY的元素
	   this.containsKey = function(_key) {
	       var bln = false;
	       try {
	           for (var i = 0; i < this.elements.length; i++) {
	               if (this.elements[i].key == _key) {
	                   bln = true;
	               }
	           }
	       } catch (e) {
	           bln = false;
	       }
	       return bln;
	   };
	  //获取map的所有values
	  this.values = function() {
	       var arr = new Array();
	       for (var i = 0; i < this.elements.length; i++) {
	           arr.push(this.elements[i].value);
	       }
	       return arr;
	   };
	  //获取map的所有keys
	  this.keys= function() {
	       var arr = new Array();
	       for (var i = 0; i < this.elements.length; i++) {
	           arr.push(this.elements[i].key);
	       }
	       return arr;
	   };
	   //获取数组
	   this.getArray= function(){
	   	var arr = new Array();
	   	for (var i = 0; i < this.elements.length; i++) {
	           arr.push({
		            key : this.elements[i].key,
		            value : this.elements[i].value
		         });
	       }
	       return arr;
	   };
	}
//********************************************	
	$(document).ready(function() {
		querySwichDiv();
	});
	//查询列表
	function querySwichDiv(){
		//加载第一页出单机构
		querySwich(1);
	}
	function querySwich(pageIndex){
		var size = 8;
		var dptCde = $.trim($('#dptCde').val());
		loadSwich({size:size,current:pageIndex,dptCde:dptCde});
	};
	function openKG(obj,id){
		var editTr = $(obj).parent('td').parent('tr')[0];
		var deptCode = editTr.childNodes[2].innerHTML;
		/**关闭*/
		if(id==1){
			$.dialog({
				type: "warn",//success,error
				content: "您确定要关闭吗？(此操作将清空已配置保额上限！)",
				onOk: function() {
					if(deptCode){
						deleteSwichId(deptCode,1);
					}else{
						$.message("error","数据有误请重新查询");	
					}
				}
			});
		}else if(id==2){
			$.dialog({
				type: "warn",//success,error
				content: "您确定要删除吗？(此操作将清空已配置保额上限！)",
				onOk: function() {
					if(deptCode){
						deleteSwichId(deptCode,2);
					}else{
						$.message("error","数据有误请重新查询");	
					}
				}
			});
		}else{
			/**打开*/
			addSwichId(deptCode,obj);
		}
	}
	//打开
	function addSwichId(deptCode,obj){
		$.openLoading();
		$.ajax({
			url : "<%=path%>/XBTSwitch/addXbtSwitch?"+new Date().getTime(),
			type : 'POST',
			async : true,
			data:{'deptCode':deptCode},
			dataType:'json',
			success:function(result){
				$.closeLoading();
				if(result.result=='success'){
					$.message("success","打开成功");
			/* 		$(obj).parent('td').parent('tr')[0].childNodes[4].innerHTML="打开"
 					$(obj).parent('td').html('<a href="javascript:void(0)"onclick="openKG(this,1);">关闭</a>') */
					querySwich(1)
				}else{
					$.message(result.result,result.message);
				}
			}
		});
	}
	//关闭
	function deleteSwichId(deptCode,obj){
		$.openLoading();
		$.ajax({
			url : "<%=path%>/XBTSwitch/delXbtSwitch?"+new Date().getTime(),
			type : 'POST',
			async : true,
			data:{deptCode:deptCode},
			dataType:'json',
			success:function(result){
				$.closeLoading();
				if(result.result=='success'){
					if(obj==1){
						$.message("success","关闭成功");
					}else if(obj==2){
						$.message("success","删除成功");
					}
					/* $(obj).parent('td').parent('tr')[0].childNodes[4].innerHTML="关闭"
					$(obj).parent('td').html('<a href="javascript:void(0)"onclick="openKG(this,0);return false">打开</a>');
 */				querySwich(1);
				}else{
					$.message(result.result,result.message);	
				}
			}
		});
	}
	
	//根据传入的参数，加载相应的出单机构
	function loadSwich(param){
		$.openLoading();
		$.ajax({
			url : "<%=path%>/XBTSwitch/querySwichList?"+new Date().getTime(),
			type : 'POST',
			async : true,
			data:param,
			dataType:'json',
			success:function(page){
				$.closeLoading();
				if($.validate(page))return;
				var fieldNames;
				var tableContent;
				var radioObj ="<input class='input_fxk' name='radioDept' type='radio'/>";
				if('1'==page.map.XBT_DPT){
					$("#statusDept").css('display','none');
					fieldNames = "deptCode@TDH,deptCode,deptName";
					var lastbutton = "<input type='button' onclick='openKG(this,2)' value='删除' class='input_button_1'><input type='button' onclick='openEditLimitDiv(this)' value='配置保额上限' style='font-size:12px' class='input_button_2'>";
					tableContent = creatTable1(fieldNames,page,radioObj,lastbutton);
				}else{
					$("#statusDept").css('display','');
					fieldNames = "deptCode@TDH,deptCode,deptName,isMigation?[{'':'关闭'};{1:'打开'};],manage";
					tableContent = creatTable1(fieldNames,page,radioObj);
				}
				var tableObj = $("#swichTable");
				tableObj.find("tbody").remove();
				tableObj.append(tableContent);
			}
		});
	}
	//点击"请选择(出单机构)" 弹出出单机构选择层
	function openDeptDiv(){
		//加载第一页出单机构
		queryDept(1);
	}
	//加载出单机构信息前，拼接参数
	function queryDept(pageIndex){
		var size = 8;
		var deptCode = $.trim($('#deptCode_choose').val());
		var deptCname = $.trim($('#deptCname_choose').val());
		
		loadDept({size:size,current:pageIndex,deptCode:deptCode,deptCname:deptCname});
	}
	
	//根据传入的参数，加载相应的出单机构 
	function loadDept(param){
		$.openLoading();
		$.ajax({
			url : "<%=path%>/XBTSwitch/queryDeptPageByCriteria?"+new Date().getTime(),
			type : 'POST',
			async : true,
			data:param,
			dataType:'json',
			success:function(page){
				$.closeLoading();
				if($.validate(page))return;
	
				var radioObj ="<input class='input_fxk' name='radioDept' type='radio'/>";
				var fieldNames = "deptCode,deptCNname";
				var tableContent = creatTable1(fieldNames,page,radioObj);
				var tableObj = $("#deptTable");
				tableObj.find("tbody").remove();
				tableObj.append(tableContent);
				
				var strPage = creatChannelPage3(param.current,6,page.maxPage,"44");
				var pageDIV = $("#deptPageDIV");
				pageDIV[0].innerHTML="";
				pageDIV.append(strPage);
				$('#deptDiv').OpenDiv();
				bindradio();
			}
		});
	}

	//绑定单选按钮事件，选中某个单选按钮，该按钮所在行高亮显示
	function bindradio(){
		$("input[name='radioDept']").click(function(){
			$("input[name='radioDept']").parent().parent().removeClass("table_highlighter");
			$(this).parent().parent().addClass("table_highlighter");
	   	});
	}
	//点击“确定”按钮，选择出单机构
	function chooseDept(){
		var selected = $("input[name='radioDept']:checked");
		if(selected.length==0){
			$.message("error", "请选择一个出单机构");
			return;
		}
		var dptCde = selected.parent().parent().children(" td:eq(1)").html();
		$('#dptCde').val(dptCde);
		closeDeptDiv();
	}
	//重置
	function resetDept(){
		$('#dptCde').val('65');
	}
	//关闭 选择出单机构 弹出层
	function closeDeptDiv(){
		$("#deptDiv").CloseDiv();	
	}
	//全局的目前打开的限额上限机构代码
	var globalDeptCode = "";
	//点击修改保额上限
	function openEditLimitDiv(obj){
		//获取该机构的deptCode
		var editTr = $(obj).parent('td').parent('tr')[0];
		var deptCode = editTr.childNodes[2].innerHTML;//获取操作的deptCode；
		globalDeptCode = deptCode;
		var param = {dptCde:deptCode};
		//根据机构代码查条款
		//机构->方案->产品->条款
		$.openLoading();
		$.ajax({
			url : "<%=path%>/XBTSwitch/queryRiskList?"+new Date().getTime(),
			type : 'POST',
			async : true,
			data:param,
			dataType:'json',
			success:function(page){
				if($.validate(page))return;
				if(page.data.length == 0){
					$.message('error','当前机构无有效条款');
					$.closeLoading();
					return ;
				}
				//以checkbox的方式标定哪些险种被选中
				var radioObj ="<input class='input_button_1' onclick='submitLimit(this,"+deptCode+")' type='button' value='提交'/>";
				//显示内容
				var fieldNames = "prodCode,riskCode,riskName,flag,chooses,input,chooses1,input1";
				var lastbutton = radioObj;
				var tableContent = creatTable(fieldNames,page,lastbutton);
				var tableObj = $("#covInfo");
				tableObj.find("tbody").remove();
				tableObj.append(tableContent);
				writeLimit(deptCode);
				$.closeLoading();
				$("#editLimitDiv").OpenDiv();
			}
		});
		
	}
/* 	//当限额的input得到焦点时，存一下当时的值
	var limit = 0;
	function onchangeLimit(obj){
		limit = $(obj).val();
	}
	//当限额的input失去焦点时，触发事件；
	function changeLimit(obj){
		var changedLimit = $.trim($(obj).val());
		changedLimit = ~~changedLimit;
		if(changedLimit != limit){
			var editTr = $(obj).parent('td').parent('tr')[0];
			var deptCode = editTr.childNodes[2].innerHTML;//获取操作的deptCode；
			var param = {deptCode:deptCode,changedLimit:changedLimit};
			changeLimitOnOk(param , obj);
 		} */
		
//加载完条款信息后，回写保额上限
function writeLimit(deptCode){
 			var tableObj = $("#covInfo");
 			var nodesList = tableObj.children();
 			//当无条款时，直接返回
 			if(nodesList.length  == 1){
 				
 				return;
 				};
 			
 			for (var i = 0 ; i < nodesList[1].childNodes.length ; i++){
 				var productCode = nodesList[1].childNodes[i].childNodes[1].innerHTML;
 				var XBTflag = "!0";
 				var param = {productCode:productCode,loaninvoiceno:XBTflag,deptCode:deptCode};
 				$.ajax({
 					url : "<%=path%>/XBTSwitch/writeBackThisLimit?"+new Date().getTime(),
 					type : 'POST',
 					async : false,
 					data:param,
 					dataType:'json',
 					success:function(data){
 						if(data == "null"){
 							data = "";
 						}
 						nodesList[1].childNodes[i].childNodes[4].childNodes[0].value=data['AMOUNTLIMIT'];
 						nodesList[1].childNodes[i].childNodes[5].childNodes[0].value=data['DENYAMOUNTLIMIT'];

 					}
 					});
 			}
 		  for (var i = 0 ; i < nodesList[1].childNodes.length ; i++){
 	 				var productCode = nodesList[1].childNodes[i].childNodes[1].innerHTML;
 	 				var XBTflag = "0";
 	 				var param = {productCode:productCode,loaninvoiceno:XBTflag,deptCode:deptCode};
 	 				$.ajax({
 	 					url : "<%=path%>/XBTSwitch/writeBackThisLimit?"+new Date().getTime(),
 	 					type : 'POST',
 	 					async : false,
 	 					data:param,
 	 					dataType:'json',
 	 					success:function(data){
 	 						if(data == "null"){
 	 							data = "";
 	 						}
 	 						nodesList[1].childNodes[i].childNodes[6].childNodes[0].value=data['AMOUNTLIMIT'];
 	 						nodesList[1].childNodes[i].childNodes[7].childNodes[0].value=data['DENYAMOUNTLIMIT'];

 	 					}
 	 					});
 				
 			}
 			
 	
}	
 		

	//弹出修改确认窗口
	function changeLimitOnOk(param,obj){
		$.dialog({
			type: "warn",
			content: "您确定要更改最大限额么？",
			onOk: function() {
				$.openLoading();
				$.ajax({
					url : "<%=path%>/XBTSwitch/updateAmountLimit?"+new Date().getTime(),
					type : 'POST',
					async : true,
					data:param,
					dataType:'json',
					success:function(result){
						$.closeLoading();
						if(result.result=='success'){
							$.message("success","更改成功");
  							querySwich(1)
						}else{
							$.message(result.result,result.message);
						}
					}
				})
			},
		onCancel:function(){
			$(obj).val(limit);
		}
		})
	;}		
	function closeLimit(){
			
		$("#editLimitDiv").CloseDiv();
	}
	
	
	
	//提交修改限额
	function submitLimit(obj,deptCode){
	
		var editTr = $(obj).parent('td').parent('tr')[0];
		//取险种代码
		productCode = editTr.childNodes[1].innerHTML;
		//取农贷通/信保通标识
		//取保额上限
		var amountLimitXBT = $.trim(editTr.childNodes[4].childNodes[0].value);
		var denyAmountLimitXBT = $.trim(editTr.childNodes[5].childNodes[0].value);
	
		var amountLimitNDT = $.trim(editTr.childNodes[6].childNodes[0].value);
		var denyAmountLimitNDT = $.trim(editTr.childNodes[7].childNodes[0].value);
		
		if((amountLimitXBT == null || amountLimitXBT =="")&&(amountLimitNDT == null || amountLimitNDT =="")){
			$.message("error","请输入有效的限额信息");
			return ;
		}
		//json数据
		var XBTloaninvoiceno = "!0";
		var paramXBT = {productCode:productCode,loaninvoiceno:XBTloaninvoiceno,amountLimit:amountLimitXBT,denyAmountLimit:denyAmountLimitXBT,deptCode:deptCode};
		var NDTloaninvoiceno = "0";
		var paramNDT = {productCode:productCode,loaninvoiceno:NDTloaninvoiceno,amountLimit:amountLimitNDT,denyAmountLimit:denyAmountLimitNDT,deptCode:deptCode};
		//新增一条信保通limit数据
		$.openLoading();
		if(!(amountLimitXBT == null || amountLimitXBT =="")){
			$.ajax({
				url : "<%=path%>/XBTSwitch/insertAmountLimit?"+new Date().getTime(),
				type : 'POST',
				async : true,
				data:paramXBT,
				dataType:'json',
				success:function(result){	
					$.closeLoading();		
					if(result.result=='success'){
						$.message("success","添加成功");
						return ;
					}
					
					//当该条限额已经存在
					else if(result.message == '已存在限额'){
						$.dialog({
							type: "warn",
							content: "已存在此条信保通限额信息，您确定要更改最大限额么？",
							onOk: function() {
								$.openLoading();
								$.ajax({
									url : "<%=path%>/XBTSwitch/updateAmountLimit?"+new Date().getTime(),
									type : 'POST',
									async : true,
									data:paramXBT,
									dataType:'json',
									success:function(result){
										$.closeLoading();
										if(result.result=='success'){
											$.message("success","更改成功");
										}else{
											$.message(result.result,result.message);
										}
									}
								})
							return ;
								},
						})
					}
				}
			});	
		}
		
		if(!(amountLimitNDT == null || amountLimitNDT =="")){
			$.ajax({
				url : "<%=path%>/XBTSwitch/insertAmountLimit?"+new Date().getTime(),
				type : 'POST',
				async : true,
				data:paramNDT,
				dataType:'json',
				success:function(result){
				
					$.closeLoading();
					
					if(result.result=='success'){
						$.message("success","添加成功");
						return ;
					}
					
					//当该条限额已经存在
					else if(result.message == '已存在限额'){
						
					
						$.dialog({
							type: "warn",
							content: "已存在此条农贷通限额信息，您确定要更改最大限额么？",
							onOk: function() {
								$.openLoading();
								$.ajax({
									url : "<%=path%>/XBTSwitch/updateAmountLimit?"+new Date().getTime(),
									type : 'POST',
									async : true,
									data:paramNDT,
									dataType:'json',
									success:function(result){
										$.closeLoading();
										if(result.result=='success'){
											$.message("success","更改成功");
										}else{
											$.message(result.result,result.message);
										}
									}
								})
							return ;
								},
						})
					}
				}
			});
		}
		
		
	}
	
	
	
	</script>
</head>
<body >
	<div class="current">
           <table class="current_table_1">
              <tbody>
                <tr class="f2">
                  <td>
                    <img src="./images/current_1.jpg">
                  </td>
                  <td class="current_table_1_td">
                    <img src="images/current_1.png">&nbsp;您现在的位置：&nbsp;
                      <span style=" color:#136bab; ">新意健险产品管理
                      <span style="padding:0 5px; font-weight:bold; line-height:28px;">&gt;</span>信保通开关
                  </span>
                  </td>
                  <td><img src="./images/current_3.jpg"></td>
              </tr>
           </tbody>
         </table>
      </div>
		
		<table class="table_02" id="table">
			<tr>
				<td>
					<table class="search_table">
						<tr height="30px">
						 	<td  style="width:'20%' height:'30';text-align: center;">
								出单机构：	<input id="dptCde" readonly="readonly"  style="background-color: #ccc;" class="input_text" value="65"><span class="red">*</span>&nbsp;
	                  	        <input type="button"  class="input_button_2" id="searchDeptBtn"  value="请选择" onClick="openDeptDiv()"/>
								<input type="button" class="input_button_1" id="searchBtn" value="查询" onClick="querySwich(1)" />&nbsp;
								<input type="button" class="input_button_1" id="" value="重置" onClick="resetDept()" />&nbsp;
							</td>
						</tr>
						<tr height="30px">
						</tr> 
					</table>
				</td>
			</tr>
			<tr>
				<td>
				</td>
			</tr>
			<tr>
				<td>
					<table id="swichTable" class="content_table_1">
						<thead>
							<tr class="f1">
								<th style="width: 10%">选择</th>
								<th>机构代码</th>
								<th style="width: 20%">机构名称</th>
								<th style="width: 10%;display: none" id="statusDept" >状态</th>
								<th>操作</th>
							</tr>
						</thead>
						<tbody>
						</tbody>
					</table>
				</td>
			</tr>
		</table>
	<!-- begin ------------------------出单机构 DIV 默认隐藏--------------------------->
	<div id="deptDiv" style="display:none;width:80%;">
		<div class="table_title_div">
			<table class="table_title" style='width:100%;height: 20px;'>
				<tr>
				<td width="10%"></td>
				<td width="80%" id="interfaceName"></td>
				<td width="10%" align="right"><img src="./images/closedown.gif" alt="关闭"  onclick="closeDeptDiv()"/></td>
				</tr>
			</table>
		</div>
		<table class="table_02" style="height:180px;" align="center">
			<tr>
				<td>
					<table class="search_table">
						<tr height="30px">
							<td colspan="3" style="text-align:center">
							机构代码：<input name="txt3"  id="deptCode_choose" class="input_text" value='65'/>&nbsp;&nbsp;
							机构名称：<input name="txt3" id="deptCname_choose" class="input_text" />
								       <input type="button"  class="input_button_1" value="查询" onClick="queryDept(1)"/>
							</td>
						</tr>
					</table>
				</td>
			</tr>
			<tr>
				<td>
					<table id="deptTable"  class="content_table_1">
						<thead>
							<tr class="f1">
			                  <th style="width:5%">选择</th>
			                  <th style="width:45%">机构代码</th>
			                  <th style="width:50%">机构名称</th>
			              	</tr>
						</thead>
						<tbody>
						</tbody>
					</table>
					<div id="deptPageDIV"  class="page"></div>
				</td>
			</tr>
		</table>
		<div align="center" >
		  <input type="button" value="确定" onclick="chooseDept()" class="input_button_3"/>&nbsp;&nbsp;&nbsp;
		  <input type="button" value="取消" onclick="closeDeptDiv()" class="input_button_3"/>
		</div>
	</div>
<!-- end ------------------------出单机构 DIV 默认隐藏--------------------------->	

<!--begin------------------------修改保额上限DIV 默认隐藏--------------------------->
	<div id="editLimitDiv" style="display:none;width:100%; overflow:auto; top:25px" >
		<div class="table_title_div">
			<table class="table_title" style='width:100%;height: -20px;'>
				<tr>
				<td width="10%"></td>
				<td width="80%" id="interfaceName"></td>
				<td width="10%" align="right"><img src="./images/closedown.gif" alt="关闭"  onclick="closeLimit()"/></td>
				</tr>
			</table>
		</div>
		<table class="table_02" style="height:180px;" align="center">
			<tr>
				<td>
					<table id="covInfo"  class="content_table_1">
						<thead>
							<tr class="f1">
							  <th style="width:10%">产品代码</th>
							  <th style="width:8%">条款代码</th>
			                  <th style="width:40%">条款名称</th>
			                  <th style="width:8%">险种标志</th>
			                  <th style="width:8%">信保通最高保额上限</th>
			               	  <th style="width:8%">信保通拒保保额上限</th>
			                  <th style="width:8%">农贷通最高保额上限</th>
			                  <th style="width:8%">农贷通拒保保额上限</th>            
			        		<th style="width:6%">操作</th>
			              	</tr>
						</thead>
						<tbody>
						</tbody>
					</table>
				</td>
			</tr>
		</table>
		
	</div>
	<!-- end ------------------------修改保额上限DIV 默认隐藏--------------------------->
</body>
</html>